package com.s;

import com.c1.C;
import com.c1.rpc.ServerData;
import com.s.core.persist.PersistService;
import com.s.core.root.Ad;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import javax.swing.*;
import java.net.URISyntaxException;
import java.security.CodeSource;
import java.security.ProtectionDomain;

/**
 * @author zhangjiangnan
 */
@SpringBootApplication
@EnableCaching
@Slf4j
public class S implements ApplicationContextAware, ApplicationListener<ContextRefreshedEvent> {
    public static ServerData serverData;
    public static PersistService persistService;
    public static final boolean IS_JAR = isJar();

    public static void main(String[] args) throws Exception {
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel");
        new SpringApplicationBuilder().sources(S.class).web(false).run(args);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        serverData = applicationContext.getBean(ServerData.class);
        persistService = applicationContext.getBean(PersistService.class);
    }

    @SneakyThrows
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        Ad.me();
        C.start();
    }

    private static boolean isJar() {
        ProtectionDomain protectionDomain = S.class.getProtectionDomain();
        CodeSource codeSource = protectionDomain.getCodeSource();
        if (codeSource != null) {
            try {
                java.net.URL location = codeSource.getLocation();
                return location.toURI().toString().startsWith("jar");
            } catch (URISyntaxException e) {
                throw new RuntimeException();
            }
        }
        throw new RuntimeException();
    }
}
